﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.ComponentModel;

public delegate void Action(Object obj , EventArgs e);

namespace MetroTube.UI
{
    public class WebClientDownloadManager
    {
        public event Action DownloadProgress;
        public event Action DownloadCompleted;

        private readonly Dictionary<WebClient, int> _clients = new Dictionary<WebClient, int>();
        
        public void Add(WebClient client)
        {
            if (client == null)
                throw new ArgumentNullException("client");

            if (_clients.ContainsKey(client))
                return;

            client.DownloadProgressChanged += (s, e) =>
            {
                _clients[(WebClient)s] = e.ProgressPercentage;

                //Console.WriteLine("webClient progress percentage:{0}", e.ProgressPercentage);

                ProgressChanged((WebClient)s, e);
            };

            client.DownloadFileCompleted += (s, e) =>
            {
                Remove((WebClient)s);

                Console.WriteLine("webClient Remove");

                ClientsChanged((WebClient)s, e);
            };

            _clients.Add(client, 0);

        }

        private void Remove(WebClient client)
        {
            if (client == null)
                throw new ArgumentNullException("client");

            if (!_clients.ContainsKey(client))
                return;

            _clients.Remove(client);
        }

        private void ProgressChanged(WebClient s, EventArgs e)
        {
            if (DownloadProgress != null)
            {
                DownloadProgress(s, e);
            }
        }

        private void ClientsChanged(WebClient s, EventArgs e)
        {
            if (DownloadCompleted != null)
            {
                DownloadCompleted(s, e);
            }
        }

        public int ClientsProgress
        {
            get
            {
                if (_clients.Count == 0)
                    return 100;
                
                int progress = _clients.Sum(client => client.Value);

                return progress / _clients.Count;
            }
        }

        public int ClientsCount
        {
            get
            {
                return _clients.Count;
            }
        }

    }
}